package com.yin.myproject.mq.util;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.ResourceBundle;
import java.util.concurrent.TimeoutException;

/**
 * Created by Eason on 2017/6/22.
 */
public class ConnectionUtil {

    private final ResourceBundle bundle = ResourceBundle.getBundle("mq");
    private Connection conn;

    private ConnectionUtil() throws IOException, TimeoutException {
        String userName = bundle.getString("userName");
        String password = bundle.getString("password");
        String virtualHost = bundle.getString("virtualHost");
        String hostName = bundle.getString("hostName");
        Integer portNumber = Integer.parseInt(bundle.getString("portNumber"));
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername(userName);
        factory.setPassword(password);
        factory.setVirtualHost(virtualHost);
        factory.setHost(hostName);
        factory.setPort(portNumber);
        conn = factory.newConnection();
    }

    public synchronized Connection getConnection() {
        if (conn == null) {
            try {
                new ConnectionUtil();
            } catch (Exception e) {
            }
        }
        return conn;
    }
}
